import nodemailer from 'nodemailer';

import {
	decryptoAES
} from './Component/Crypto.js';

import {
	setMailToken,
	verToken
} from './Component/token.js';

import {
	reactServer
} from '../server.js';

import {
	mysqlConnectPromise,
	mysqlQueryPromise
} from './Component/MySQLPromise.js';

import {
	respondJson,
	respondReqDataMalformation,
	respondServerSQLError,
	respondServerQueryError
} from './Component/Respond.js';

export const sendResetMail = async (req, res, next) => {

	let username = req.body.username;
	let email = req.body.email;

	if (!(username && email)) {
		respondReqDataMalformation(res);
		return;
	}

	let pool = req.app.locals.pool;

	let connection = await mysqlConnectPromise(pool);

	if (!connection) {
		respondServerSQLError(res);
		return;
	}

	let results = await mysqlQueryPromise(connection, `SELECT email from users where username like '${username}'`);

	if (!results) {
		respondServerQueryError(connection, res);
		return;
	} else if (results.length == 0) {
		respondJson(connection, res, 200, {
			status: false,
			errinfo: 'no such user!'
		})
		return;
	}

	if (email != results[0].email) {
		respondJson(connection, res, 200, {
			status: false,
			errinfo: 'email incorrect!'
		})
		return;
	}

	setMailToken(username, email).then((data) => smail(data));

	function smail(data) {
		var token = reactServer + '/chanpass?token=' + data;

		var index = `
			<html xmlns="http://www.w3.org/1999/xhtml">
			<body class="main full-padding" style="margin: 0;padding: 0;-webkit-text-size-adjust: 100%;">
				<table class="wrapper" style="border-collapse: collapse;table-layout: fixed;min-width: 320px;width: 100%;background-color: #fff;" cellpadding="0" cellspacing="0" role="presentation">
				<tbody><tr><td>
					<div>
					<div class="layout one-col fixed-width stack" style="Margin: 0 auto;max-width: 600px;min-width: 320px; width: 320px;width: calc(28000% - 167400px);overflow-wrap: break-word;word-wrap: break-word;word-break: break-word;">
						<div class="layout__inner" style="border-collapse: collapse;display: table;width: 100%;background-color: #bacfda;">
						<div class="column" style="text-align: left;color: #1a3541;font-size: 16px;line-height: 24px;font-family: Lato,Tahoma,sans-serif;">
							<div style="Margin-left: 20px;Margin-right: 20px;Margin-top: 24px;">
							<img style="border: 0;display: block;height: auto;width: 100px;max-width: 180px;" src="cid:01" alt="" width="180" />
							</div>
							<div style="Margin-left: 20px;Margin-right: 20px;">
							<div style="vertical-align: middle;">
								<h1 style="Margin-top: 0;Margin-bottom: 20px;font-style: normal;font-weight: normal;color: #264b65;font-size: 36px;line-height: 43px;text-align: center;"><strong>&#26356;&#25913;&#20320;&#30340;&#23494;&#30721;</strong></h1>
							</div>
							</div>
							<div style="Margin-left: 20px;Margin-right: 20px;">
							<div style="vertical-align: middle;">
								<p style="Margin-top: 0;Margin-bottom: 20px;text-align: center;">&#28857;&#20987;&#19979;&#26041;&#38142;&#25509;&#36827;&#34892;&#26356;&#25913;&#65292;&#22914;&#26524;&#19981;&#26159;&#26412;&#20154;&#25805;&#20316;&#35831;&#19981;&#35201;&#28857;&#20987;&#19979;&#38754;&#25353;&#38062;&#24182;&#21450;&#26102;&#21453;&#39304;&#32473;&#25105;&#20204;&#12290;</p>
							</div>
							</div>
							<div style="Margin-left: 20px;Margin-right: 20px;">
							<div class="btn btn--flat btn--large" style="Margin-bottom: 20px;text-align: center;">
								<a style="border-radius: 4px;display: inline-block;font-size: 14px;font-weight: bold;line-height: 24px;padding: 12px 24px;text-align: center;text-decoration: none !important;transition: opacity 0.1s ease-in;color: #264b65 !important;background-color: #fac84a;font-family: sans-serif;" href="${token}">&#21069;&#24448;&#26356;&#25913;</a>
							</div>
							</div>
							<div style="font-size: 12px;font-style: normal;font-weight: normal;line-height: 19px;" text-align="center">
							<img class="gnd-corner-image gnd-corner-image-center gnd-corner-image-bottom" style="border: 0;display: block;height: auto;width: 100%;max-width: 900px;" alt="" width="600" src="cid:02" />
							</div>
						</div>
						</div>
					</div>
					</div>
				</td></tr></tbody>
				</table>
			</body>
			</html>`;

		let transporter = nodemailer.createTransport({
			host: 'smtp.163.com',
			service: "163", //邮箱类型 例如service:'163'
			secure: true, //是否使用安全连接，对https协议的
			// port: 465, //qq邮件服务所占用的端口
			auth: {
				user: "dwmzwxh@163.com", //开启SMTP的邮箱，发件人
				pass: "ZHIGEMLYFQMVPELV" // qq授权码
			}
		})

		let options = {
			from: 'dwmzwxh@163.com', //发送方
			to: email, //接收方
			subject: '重置您的账户密码', //邮件主题
			// text: "测试",//邮件正文
			html: index, //html模板
			//附件信息
			attachments: [{
					filename: 'Logo.png',
					path: './public/index/images/Logo.png',
					cid: '01'
				},
				{
					filename: 'bg.png',
					path: './public/index/images/bg.png',
					cid: '02'
				}
			]
		}

		transporter.sendMail(options, (err, info) => {
			if (err) {
				respondJson(connection, res, 200, {
					status: false,
					errinfo: 'send mail failure!'
				})
			} else {
				respondJson(connection, res, 200, {
					status: true,
					info: '发送重置密码邮件成功!'
				})
			}
		})
	}

}

export const changePassword = async (req, res, next) => {

	const body = req.body;
	const info = req.data;

	console.log(info, body)

	let password = body.password;

	if (!password) {
		respondReqDataMalformation(res);
		return;
	}

	let newPass = decryptoAES(password);

	let pool = req.app.locals.pool;

	let connection = await mysqlConnectPromise(pool);

	if (!connection) {
		respondServerSQLError(res);
		return;
	}

	let results = await mysqlQueryPromise(connection, `UPDATE users SET password='${newPass}' where username like '${info.name}'`);

	if (!results) {
		respondServerQueryError(connection, res);
		return;
	}

	respondJson(connection, res, 200, {
		status: true,
		info: 'update success!'
	})

	return;

}